Skip to content

Conversation

@DevMunky
Copy link
Contributor

@DevMunky DevMunky commented Jul 25, 2025

Fix issues with tasks being "aborted" (throwing exceptions when queued) upon the thread pool filling.

  • Use an ArrayBlockingQueue with a capacity of 16 to sit between the decision to make a new thread or wait for an existing one to finish working and take up the task.

  • Implement a task rejection handler to log the occurrence and execute the task on the caller thread instead of throwing.

Summary by CodeRabbit

  • Refactor

    • Improved thread pool management for asynchronous tasks, introducing explicit limits and enhanced task queuing for better performance and reliability.
    • Enhanced logging for situations when the thread pool is full.
  • New Features

    • Added new constants to allow for clearer configuration of thread pool behavior.

DevMunky added 4 commits June 27, 2025 19:02
* Implement a maximum number of threads to exist in the pool.

* Implement a threshold to stop creating platform threads and leverage virtual threads instead.

* Implement a core size of threads, those of which never leave the pool to buffer inactivity.
* Removed MAX_THREAD_POOL_SIZE and VIRTUAL_THREAD_THRESHOLD, replacing them with MAX_PLATFORM_THREADS and MAX_VIRTUAL_THREADS.

* Improve documentation to include @sees for java implementation specifics.

Took 7 minutes
…FORM_THREADS and MAX_VIRTUAL_THREADS.

* I forgot.

Took 4 minutes
…d) upon the thread pool filling.

* Use an ArrayBlockingQueue with a capacity of 16 to sit between the decision to make a new thread or wait for an existing one to finish working and take up the task.

* Implement a task rejection handler to log the occurrence and execute the task on the caller thread instead of throwing.

Took 54 minutes
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 25, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The cached thread pool dispatcher was reimplemented with a custom ThreadPoolExecutor using increased core and max pool sizes, a bounded ArrayBlockingQueue for task buffering, and a refined thread creation strategy that uses platform threads up to a limit and virtual threads thereafter. A custom rejection handler logs pool status and runs rejected tasks in the caller thread. The dispatcher is exposed as a coroutine dispatcher via an extension property.

Changes

File(s) Change Summary
engine/engine-core/src/main/kotlin/com/typewritermc/core/utils/CachedThreadPoolDispatcher.kt Reimplemented cached thread pool with custom ThreadPoolExecutor, increased thread limits, bounded task queue, refined thread factory using platform and virtual threads, added rejection handler with logging, introduced sizing constants, and exposed dispatcher as coroutine dispatcher.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant CoroutineDispatcher
    participant ThreadPoolExecutor
    participant PlatformThread
    participant VirtualThread

    Caller->>CoroutineDispatcher: Dispatch coroutine/task
    CoroutineDispatcher->>ThreadPoolExecutor: Submit task
    alt Platform threads < MAX_PLATFORM_THREADS
        ThreadPoolExecutor->>PlatformThread: Create and run task (daemon)
    else
        ThreadPoolExecutor->>VirtualThread: Create and run task
    end
    alt Task queue full
        ThreadPoolExecutor->>Caller: Run rejected task in caller thread (CallerRunsPolicy)
        ThreadPoolExecutor->>Logger: Log rejection and pool status
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

Poem

In the warren of threads, both platform and light,
A rabbit now bounds through the day and the night.
With queues now bounded and tasks in a line,
No more runaway threads—just order, by design.
🐇✨ Dispatcher hops, and all runs just right!

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 469cb7a and 5e5f7c3.

📒 Files selected for processing (1)
  • engine/engine-core/src/main/kotlin/com/typewritermc/core/utils/CachedThreadPoolDispatcher.kt (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: DevMunky
PR: gabber235/Typewriter#357
File: engine/engine-core/src/main/kotlin/com/typewritermc/core/utils/CachedThreadPoolDispatcher.kt:58-58
Timestamp: 2025-07-10T04:45:22.886Z
Learning: In the Typewriter project's CachedThreadPoolDispatcher.kt, the CORE_POOL_SIZE constant is intentionally set to 6 even though it may exceed MAX_PLATFORM_THREADS on systems with few CPU cores. This is documented behavior where virtual threads will be used in the core pool when MAX_PLATFORM_THREADS < CORE_POOL_SIZE, and should not be flagged as an issue.
engine/engine-core/src/main/kotlin/com/typewritermc/core/utils/CachedThreadPoolDispatcher.kt (1)

Learnt from: DevMunky
PR: #357
File: engine/engine-core/src/main/kotlin/com/typewritermc/core/utils/CachedThreadPoolDispatcher.kt:58-58
Timestamp: 2025-07-10T04:45:22.886Z
Learning: In the Typewriter project's CachedThreadPoolDispatcher.kt, the CORE_POOL_SIZE constant is intentionally set to 6 even though it may exceed MAX_PLATFORM_THREADS on systems with few CPU cores. This is documented behavior where virtual threads will be used in the core pool when MAX_PLATFORM_THREADS < CORE_POOL_SIZE, and should not be flagged as an issue.

🔇 Additional comments (2)
engine/engine-core/src/main/kotlin/com/typewritermc/core/utils/CachedThreadPoolDispatcher.kt (2)

32-87: Well-structured constants with comprehensive documentation!

The constants are properly defined with clear documentation explaining the thread pool behavior, especially the rejection handling strategy and task queue buffering. The TASK_QUEUE_SIZE of 16 provides an appropriate buffer to prevent immediate task rejection, addressing the core issue mentioned in the PR.


114-121: Rejection handler properly implements the buffering strategy!

The custom rejection handler effectively addresses the PR's core objective by logging rejection details and delegating to CallerRunsPolicy instead of throwing exceptions. This ensures tasks are executed on the caller's thread when the pool is saturated, preventing task abortion.

* Fix MAX_PLATFORM_THREADS actually being += 1 during runtime (> instead of >=)

* Fix the info logging from a rejected task returning an incorrect number of idle threads.

Took 8 minutes
@gabber235
Copy link
Owner

Looking at this code, would I still be able to spawn 10.000 coroutines in an instant? What would happen?

I would like to just have them queued if there is no available thread

@DevMunky
Copy link
Contributor Author

DevMunky commented Jul 25, 2025

Right now, any task that exceeds the limit of the taskQueue and the thread counts gets executed by the caller thread. If we wanted to implement what you are saying, then we would have to create our own mechanism, as the taskQueue filling up is what signifies more threads should be created by the thread pool.

@DevMunky
Copy link
Contributor Author

Implemented this but it may need a better approach. Let me know if you are certain we want that functionality, and I will commit it.

@gabber235
Copy link
Owner

Let's do this in two phases. I do want this functionality because executing on the callers thread is going to lead to a ton of subtle bugs which will be basically impossible to diagnose. Simply because it breaks down the implicit contract

@DevMunky
Copy link
Contributor Author

Well the bigger question is do you want a task rejection handler that handles too many tasks as they come in, or do you just want to store everything.

@DevMunky DevMunky marked this pull request as draft July 26, 2025 21:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants